<template>
  <el-dialog v-bind="$attrs" v-on="$listeners">
    <el-form
      :model="params"
      :rules="majorRules"
      ref="form"
      label-width="100px"
      size="mini"
    >
      <el-form-item label="专业名称:" prop="major_name">
        <el-input v-model="params.major_name"></el-input>
      </el-form-item>
      <el-form-item label="所属院系:" prop="major_department_id">
        <el-select clearable v-model="params.major_department_id">
          <el-option label="请选择" value="" disabled></el-option>
          <el-option
            v-for="d in departments"
            :key="d.department_id"
            :label="d.department_name"
            :value="d.department_id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button size="mini" @click="change()">取消</el-button>
      <el-button type="primary" size="mini" @click="confirm()">添加</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { selectDepartmentOptions } from "@/api";
import majorRules from "@/rules/majorRules";
import { insertNewMajor } from "@/api/major";

export default {
  data() {
    return {
      departments: [],
      majorRules,
      params: {
        major_name: "",
        major_department_id: "",
      },
    };
  },
  methods: {
    async initOptions() {
      let { data } = await selectDepartmentOptions({ department_name: "" });
      this.departments = data;
    },
    change() {
      this.$emit("update:visible", false);
      // 重置表单数据
      this.$refs.form.resetFields();
      // 重置表单状态
      this.$refs.form.clearValidate();
    },
    async confirm() {
      await this.$refs.form.validate();
      await insertNewMajor(this.params);
      this.$emit("reload");
      this.$emit("update:visible", false);
      // this.params = {};
      // 重置表单数据
      this.$refs.form.resetFields();
      // 重置表单状态
      this.$refs.form.clearValidate();
    },
  },
  created() {
    this.initOptions();
  },
};
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
</style>
